package com.android.multiplesmart.activity;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.multiplesmart.R;
import com.tencent.tbs.reader.ITbsReader;
import com.tencent.tbs.reader.ITbsReaderCallback;
import com.tencent.tbs.reader.TbsFileInterfaceImpl;

public class LocaActivity extends  BaseActivity{
    boolean isInit;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.locallayout);
//        String filePath = getIntent().getStringExtra("filePath");
//        String fileExt = getIntent().getStringExtra("fileExt");
        initView();
        initListener();
        // 初始化Engine，见下文
        int ret = initEngine();
        if(ret != 0) {
            Toast.makeText(getApplicationContext(), "初始化Engine失败 ret = " + ret, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "初始化Engine成功", Toast.LENGTH_SHORT).show();
            isInit = true;
            openFile();
        }


    }

    private FrameLayout mFlRoot; //内容显示区域
    private RelativeLayout mRl; //自定义标题栏
    private boolean isDestroyed = false;





    @Override
    public void onClick(View v) {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initView() {
        mFlRoot = findViewById(R.id.content);
        mRl = findViewById(R.id.reader_top);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            destroy();
        }
    }


    private void openFile() {
        //设置回调
        ITbsReaderCallback callback = new ITbsReaderCallback() {
            @Override
            public void onCallBackAction(Integer actionType, Object args, Object result) {
                Log.i("LocaActivity", "actionType=" + actionType + "，args=" + args + "，result=" + result);
                if (ITbsReader.OPEN_FILEREADER_STATUS_UI_CALLBACK == actionType) {
                    if (args instanceof Bundle) {
                        int id = ((Bundle) args).getInt("typeId");
                        if (ITbsReader.TBS_READER_TYPE_STATUS_UI_SHUTDOWN == id) {
                            finish();       // 加密文档弹框取消需关闭activity
                        }
                    }
                }
            }
        };

        //设置参数
        Bundle param = new Bundle();
        param.putString("filePath", "/storage/emulated/0/Android/data/com.tencent.tbs.ydh/cache/Download/zh-Hans.pptx");
        param.putString("fileExt", "pptx"); // 文件后缀名，如文件名为test.pdf，则只需要传入"pdf"
        param.putString("tempPath", getExternalFilesDir("temp").getAbsolutePath());
        //调用openFileReader打开文件
        mFlRoot.post(new Runnable() {
            @Override
            public void run() {
                int height = mFlRoot.getHeight();
                // 自定义layout模式必须设置这个值，否则可能导致文档内容显示不全
                param.putInt("set_content_view_height", height);
                int ret = TbsFileInterfaceImpl.getInstance().openFileReader(
                        LocaActivity.this, param, callback, mFlRoot);
            }
        });
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        destroy();
    }
    // 销毁资源使用onpause + ondestroy的方式。避免onDestroy延迟回调
    private void destroy()  {
        if (isDestroyed) {
            return;
        }
        // 回收资源
        mFlRoot.removeAllViews(); //移除内容显示区域layout
        TbsFileInterfaceImpl.getInstance().closeFileReader(); //关闭fileReader
        isDestroyed = true;
    }

    //横竖屏切换
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mFlRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mFlRoot.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int w = mFlRoot.getWidth();
                int h = mFlRoot.getHeight();
                TbsFileInterfaceImpl.getInstance().onSizeChanged(w, h);
            }
        });
    }





    public void initEngineAsync() {
        //设置licenseKey
        TbsFileInterfaceImpl.setLicenseKey("oOFex4c7dR+rd7W/G22bge9ZqhsNvFt3Hl5b4LcOxT+x7fiFb1RIlKznvRLtY8dC");

        ITbsReaderCallback callback = new ITbsReaderCallback() {
            @Override
            public void onCallBackAction(Integer actionType, Object args, Object result) {
                Log.i("LocaActivty", "actionType=" + actionType + "，args=" + args + "，result=" + result);
                // ITbsReader.OPEN_FILEREADER_ASYNC_LOAD_READER_ENTRY_CALLBACK 的值为 7002，不是错误码
                if (ITbsReader.OPEN_FILEREADER_ASYNC_LOAD_READER_ENTRY_CALLBACK == actionType) {
                    int ret = (int)args; // 错误码为actionType == 7002时 args的值
                    if (ret == 0) {

                        // 初始化成功
                    } else {
                        // 初始化失败
                    }
                }
            }
        };
        if (!TbsFileInterfaceImpl.isEngineLoaded()) {
            TbsFileInterfaceImpl.initEngineAsync(this, callback);
        }
    }

    public int initEngine() {
        //设置licenseKey
        TbsFileInterfaceImpl.setLicenseKey("oOFex4c7dR+rd7W/G22bge9ZqhsNvFt3Hl5b4LcOxT+x7fiFb1RIlKznvRLtY8dC");

        int ret = -1;

        //初始化Engine
        if (!TbsFileInterfaceImpl.isEngineLoaded()) {
            ret = TbsFileInterfaceImpl.initEngine(this);
        }

        return ret;
    }

}
